package cn.yuanqiao.web.controller.archive.detail;/**
 * @author 赵常飞
 * @date 2023/6/28 15:42
 */

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantYqda;
import cn.yuanqiao.archive.appManager.domain.TenantYqdaDocument;
import cn.yuanqiao.archive.appManager.domain.YqSy;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqdaDocumentMapper;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.appManager.service.IYqSyService;
import cn.yuanqiao.archive.detail.service.IDetailService;
import cn.yuanqiao.archive.detail.utils.URLGeneratorForExtension;
import cn.yuanqiao.archive.utils.FileWaterMark;
import cn.yuanqiao.archive.wenjianzhengli.domain.Yqdatransdoc;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DESUtil;
import cn.yuanqiao.common.utils.ImgUtils;
import cn.yuanqiao.common.utils.PdfUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.web.page.TableDataInfo;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.context.ResponseUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.mozilla.universalchardet.UniversalDetector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @AUTHOR:赵常飞
 * @date 2023/6/28 15:42
 */
@RestController
@RequestMapping("/archive/detail")
public class DetailController extends BaseController {
    @Autowired
    private IDetailService detailService;
    @Autowired
    private TenantYqdaDocumentMapper documentMapper;
    @Autowired
    private TenantCategoryMapper categoryMapper;
    @Autowired
    private IYqSyService yqSyService;
    @Autowired
    private ITenantSysConfigService sysConfigService;


    /**
     * 获取目录信息
     *
     * @param json datatype  当前传过来的id是件id还是卷id还是项目id,0件1卷3项目
     *             id          主键
     *             intotype    获取哪一层的信息0件1卷3项目
     *             1和3不一样,比如可以通过件id获取卷和项目的信息
     * @return
     */
    @Log(title = "获取目录信息", businessType = BusinessType.SELECT)
    @PostMapping("/getdatainfo")
    public AjaxResult getdatainfo(@RequestBody JSONObject json) {
        return success(detailService.getdatainfo(json));
    }

    /**
     * 获取电子文件信息
     *
     * @param json
     * @return
     */
    @Log(title = "获取电子文件信息", businessType = BusinessType.SELECT)
    @PostMapping("/getefileinfo")
    public AjaxResult getefileinfo(@RequestBody JSONObject json) {
        return success(detailService.getefileinfo(json));
    }

    /**
     * 预览
     *
     * @param request
     * @param response docId   文件docid  *
     *                 daId       档案id     daId和categoryId二选一必填
     *                 categoryId  门类id
     * @throws Exception
     */
    @Log(title = "预览", businessType = BusinessType.OTHER)
    @PostMapping("/view")
    public void view(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Long doc_id = Long.parseLong(request.getParameter("docId"));
        String daId = String.valueOf(request.getParameter("daId"));
        String categoryId = String.valueOf(request.getParameter("categoryId"));
        TenantCategory tenantCategory = new TenantCategory();
        String catetablename = tenantCategory.getTableName();
        TenantYqda tenantYqda = new TenantYqda();
        String allftable = tenantYqda.getTableName();
        String efiletable = "";
        if (null == daId || "null".equals(daId)) {
            //tenantCategory.setCategoryId(Long.parseLong(categoryId));
            TenantCategory tenantCategory1 = categoryMapper.selectTenantCategoryByID(Long.parseLong(categoryId), new TenantCategory().getTableName());
            efiletable = tenantCategory1.getEfileTableName();
        } else {
            efiletable = documentMapper.gettablenamebydaid(Long.parseLong(daId), allftable, catetablename);
        }
        TenantYqdaDocument document = documentMapper.viewByDocid(doc_id, efiletable, new Yqdatransdoc().getTableName());
        String url = document.getDocMnt() + File.separator + document.getPath();
        logger.info(url);
        if (url.equals("null")) {
            response.sendError(404, "File not found!");
            return;
        }



        // 设置文件下载的响应头
        //response.setContentType("application/octet-stream");
        //response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");


        response.reset(); // 非常重要

        // 设置 CORS 响应头
        ResponseUtils.defaultResponse(response);

        if ("TXT".equals(document.getDocFileType())) {
            readTxtFile(url, document.getDocName(), response);
        } else {
            //在线预览，浏览器支持的文件类型都能打开
            URL u = new URL("file:///" + url);
            //response.setContentType(u.openConnection().getContentType());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + document.getRealDocName() + "\"");
            //BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(url)));
            FileInputStream inputStream = null;
            //byte[] buf = new byte[4096];
            //int len = 0;
            //OutputStream out = response.getOutputStream();
            //while ((len = br.read(buf)) > 0){
            //    out.write(buf, 0, len);
            //    out.flush(); // 定期刷新输出流
            // }
            inputStream = new FileInputStream(url);
            int len = 0;
            byte[] buf = new byte[4096];
            OutputStream out = response.getOutputStream();
            while ((len = inputStream.read(buf)) > 0) {
                out.write(buf, 0, len);
                out.flush(); // 定期刷新输出流
            }
            System.gc();
            inputStream.close();
            out.close();
        }

        /*InputStream inputStream = new FileInputStream(new File(url));
        Reader reader = new InputStreamReader(inputStream, "GBK");
        BufferedReader bufferedReader = new BufferedReader(reader);

        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        String fileContent = stringBuilder.toString();

        // 之后你可以将fileContent作为你的响应内容
        response.setContentType("text/plain; charset=GBK"); // 设置正确的编码格式
        response.setHeader("Content-Disposition", "inline; filename=\"" + document.getDocName() + "\"");
        OutputStream out = response.getOutputStream();
        out.write(fileContent.getBytes("GBK"));

        // 关闭资源
        bufferedReader.close();
        reader.close();
        inputStream.close();*/
    }

    /**
     * 获取ODF预览路径
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Log(title = "预览获取OFD文件路径", businessType = BusinessType.OTHER)
    @PostMapping("getOfdFile")
    public AjaxResult getOfdFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Long doc_id = Long.parseLong(request.getParameter("docId"));
        String daId = String.valueOf(request.getParameter("daId"));
        String categoryId = String.valueOf(request.getParameter("categoryId"));
        TenantCategory tenantCategory = new TenantCategory();
        String catetablename = tenantCategory.getTableName();
        TenantYqda tenantYqda = new TenantYqda();
        String allftable = tenantYqda.getTableName();
        String efiletable = "";
        if (null == daId || "null".equals(daId)) {
            //tenantCategory.setCategoryId(Long.parseLong(categoryId));
            TenantCategory tenantCategory1 = categoryMapper.selectTenantCategoryByID(Long.parseLong(categoryId), new TenantCategory().getTableName());
            efiletable = tenantCategory1.getEfileTableName();
        } else {
            efiletable = documentMapper.gettablenamebydaid(Long.parseLong(daId), allftable, catetablename);
        }
        TenantYqdaDocument document = documentMapper.viewByDocid(doc_id, efiletable, new Yqdatransdoc().getTableName());
        String url = document.getDocMnt() + File.separator + document.getPath();
        File file = new File(url);
        if (!file.exists()) {
            return AjaxResult.error(404, "File not found!");
        } else {
            JSONObject object = new JSONObject();
            object.put("time", String.valueOf(new Date().getTime()));
            object.put("tenantCode", SecurityUtils.getTenantCode());
            object.put("path", file.getAbsolutePath());
            object.put("userId", SecurityUtils.getUserId());
            String msg = object.toJSONString();
            logger.info(msg);
            msg = DESUtil.encrypt(msg);
            return AjaxResult.success(Base64Utils.encodeToUrlSafeString(msg.getBytes()));
        }
    }

    /**
     * ODF预览
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("viewOfd")
    public void viewOfd(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String info = request.getParameter("token");
        if (StringUtils.isEmpty(info)) {
            throw new ServiceException("参数错误");
        } else {
            String msg = new String(Base64Utils.decodeFromUrlSafeString(info));
            String fileInfo = DESUtil.decrypt(msg);
            logger.info(fileInfo);
            JSONObject object = JSONObject.parseObject(fileInfo);
            InputStream inputStream = null;
            OutputStream os = null;
            try {
                String destFilePath = object.getString("path");
                String fileName = object.getString("time") + ".ofd";
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                inputStream = new FileInputStream(new File(destFilePath));
                os = response.getOutputStream();
                byte[] bytes = new byte[2048];
                int length;
                while ((length = inputStream.read(bytes)) != -1) {
                    os.write(bytes, 0, length);
                }
                os.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * ODF云阅读
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("cloud/reading")
    public String yunyuedu(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String info = request.getParameter("token");
        String sydm = request.getParameter("sydm");
        if (StringUtils.isEmpty(info)) {
            throw new ServiceException("参数错误");
        } else {
            return URLGeneratorForExtension.url(info, sydm);
        }
    }


    /**
     * 云阅读水印
     *
     * @return
     * @throws Exception
     */
    @GetMapping("watermark")
    public Map yydSy(@RequestParam("sydm") String sydm) {
        YqSy yqSy = new YqSy();
        yqSy.setSydm(sydm);
        yqSy = yqSyService.selectYqSyBySydm(yqSy);
        /* 组织接口返回信息 */
        Map<String, Object> resultMap = new ConcurrentHashMap<>();
        resultMap.put("ret", 0);
        resultMap.put("message", "success");
        resultMap.put("data", detailService.getWatermarkData(yqSy));
        return resultMap;
    }

    @GetMapping("systemuser/permission")
    public Map getsystemUserPermission() {

        /* 组织接口返回信息 */
        Map<String, Object> resultMap = new ConcurrentHashMap<>();
        resultMap.put("ret", 0);
        resultMap.put("message", "success");
        resultMap.put("data", detailService.getPermissionData());
        return resultMap;
    }

    private void readTxtFile(String filePath, String fileName, HttpServletResponse response) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath))) {
            UniversalDetector detector = new UniversalDetector(null);
            byte[] buf = new byte[4096];
            int nread;

            while ((nread = bis.read(buf)) > 0 && !detector.isDone()) {
                detector.handleData(buf, 0, nread);
            }

            detector.dataEnd();
            //读取txt文件的编码格式
            String encoding = detector.getDetectedCharset();
            if(encoding == null){
                encoding = "GBK";
            }
            detector.reset();
            //以确定的编码格式读取文件
            OutputStream out = response.getOutputStream();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), encoding))) {
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                    sb.append(System.lineSeparator());
                }
                String fileContent = sb.toString();
                // 之后你可以将fileContent作为你的响应内容
                response.setContentType("text/plain; charset=" + encoding); // 设置正确的编码格式
                response.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
                out.write(fileContent.getBytes(encoding));
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载
     *
     * @param request
     * @param response docId   文件docid  *
     *                 daId       档案id     daId和categoryId二选一必填
     *                 categoryId  门类id
     * @throws Exception
     */
    @Log(title = "下载", businessType = BusinessType.DOWNLOAD)
    @PostMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Long doc_id = Long.parseLong(request.getParameter("docId"));
        String daId = String.valueOf(request.getParameter("daId"));
        String categoryId = String.valueOf(request.getParameter("categoryId"));
        String borrowId = String.valueOf(request.getParameter("borrowId"));
        String menuId = String.valueOf(request.getParameter("menuId"));
        String sydm = String.valueOf(request.getParameter("sydm"));
        if ("null".equals(sydm)) {
            sydm = "";
        }
        detailService.download(doc_id, daId, categoryId, borrowId, menuId, sydm, response);
    }

    @Log(title = "pdf是否加密", businessType = BusinessType.SELECT)
    @PostMapping("/pdfIsEncryption")
    public AjaxResult pdfIsEncryption(@RequestBody JSONObject object) throws Exception {
        TenantCategory tenantCategory = categoryMapper.selectTenantCategoryByID(object.getLong("categoryId"), new TenantCategory().getTableName());
        TenantYqdaDocument document = documentMapper.selectnameandpathbyDocid(object.getLong("docId"), tenantCategory.getEfileTableName());
        String url = document.getDocMnt() + File.separator + document.getPath();
        return AjaxResult.success(FileWaterMark.PdfIsEncryption(url));
    }

    /**
     * 打印
     *
     * @param request
     * @param response docId   文件docid  *
     *                 daId       档案id     daId和categoryId二选一必填
     *                 categoryId  门类id
     * @throws Exception
     */
    @Log(title = "打印", businessType = BusinessType.OTHER)
    @PostMapping("/print")
    public void print(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Long doc_id = Long.parseLong(request.getParameter("docId"));
        String daId = String.valueOf(request.getParameter("daId"));
        String categoryId = String.valueOf(request.getParameter("categoryId"));
        String sydm = String.valueOf(request.getParameter("sydm"));
        if ("null".equals(sydm)) {
            sydm = "";
        }
        TenantCategory tenantCategory = new TenantCategory();
        String catetablename = tenantCategory.getTableName();
        TenantYqda tenantYqda = new TenantYqda();
        String allftable = tenantYqda.getTableName();
        String efiletable = "";
        if (null == daId || "null".equals(daId)) {
            //tenantCategory.setCategoryId(Long.parseLong(categoryId));
            TenantCategory tenantCategory1 = categoryMapper.selectTenantCategoryByID(Long.parseLong(categoryId), new TenantCategory().getTableName());
            efiletable = tenantCategory1.getEfileTableName();
        } else {
            efiletable = documentMapper.gettablenamebydaid(Long.parseLong(daId), allftable, catetablename);
        }
        TenantYqdaDocument document = documentMapper.selectnameandpathbyDocid(doc_id, efiletable);
        String url = document.getDocMnt() + File.separator + document.getPath();
        if (url.equals("null")) {
            response.sendError(404, "File not found!");
            return;
        }

        if (StringUtils.isNotEmpty(sydm)) {
            //添加水印
            YqSy yqSy = new YqSy();
            yqSy.setSydm(sydm);
            yqSy = yqSyService.selectYqSyBySydm(yqSy);
            if (null != yqSy && StringUtils.isNotEmpty(yqSy.getSynr())) {
                if(!FileWaterMark.PdfIsEncryption(url)){
                    String fpath = url;
                    String fileFullName = fpath.substring(fpath.lastIndexOf("\\") + 1, fpath.lastIndexOf("."));
                    String prefix = fpath.substring(fpath.lastIndexOf(".") + 1);
                    String waterMarkFilepath = sysConfigService.selectConfigByKey("WATERMARKFILEPATH");
                    //生成水印文件地址
                    if (!StringUtils.isEmpty(waterMarkFilepath)) {
                        File folder = new File(waterMarkFilepath);
                        if (!folder.exists()) {
                            if (folder.mkdirs()) {

                            } else {
                                throw new RuntimeException("路径" + waterMarkFilepath + "不存在！");
                            }
                        }
                        waterMarkFilepath += fileFullName + "." + prefix;
                    } else {
                        throw new RuntimeException("没有在系统参数表配置添加水印文件保存路径WATERMARKFILEPATH字段");
                    }
                    if ("pdf".equals(prefix.toLowerCase())) {
                        FileWaterMark.pdfWaterMark(fpath, waterMarkFilepath, yqSy);
                        url = waterMarkFilepath;
                    } else if ("png".equals(prefix.toLowerCase()) || "jpg".equals(prefix.toLowerCase()) || "jpeg".equals(prefix.toLowerCase())) {
                        FileWaterMark.addPictureWaterMark(fpath, waterMarkFilepath, yqSy);
                        url = waterMarkFilepath;
                    }
                }
            }
        }

        response.reset(); // 非常重要
        // 设置 CORS 响应头
        ResponseUtils.defaultResponse(response);
        //在线预览，浏览器支持的文件类型都能打开
        URL u = new URL("file:///" + url);
        //response.setContentType(u.openConnection().getContentType());
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "inline; filename=\"" + document.getDocName() + "\"");
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(url)));
        byte[] buf = new byte[1024];
        int len = 0;
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        System.gc();
        br.close();
        out.close();
    }

    /**
     * 根据项目id获取卷列表/根据案卷id获取件列表
     * json 中
     * "fields": "BGQX,MJ", //展示字段
     * "categoryId": 0, //门类id
     * "parentId": 0, //父节点id
     * "level": 3,  //父节点类型
     * "menuId": 0, //菜单id
     * "order": "BGQX DESC", //排序
     * "searchcolumn": [    //查询框的值
     * {
     * "queryType": "4",
     * "showType": "1",
     * "column": "ND",
     * "value": "2022",
     * "valueTwo": "2023"
     * }
     * ]
     */
    @Log(title = "根据项目id获取卷列表/根据案卷id获取件列表", businessType = BusinessType.SELECT)
    @PostMapping("/getlistbyparentId")
    public TableDataInfo getlistbyparentId(@RequestBody JSONObject json) {
        List<Map<String, Object>> list = detailService.getlistbyparentId(json);
        return getDataTable(list);
    }

    @Log(title = "获取文件明细信息", businessType = BusinessType.SELECT)
    @PostMapping("/getefileinfobydocid")
    public AjaxResult getefileinfobydocid(@RequestBody JSONObject json) {
        return success(detailService.getefileinfobydocid(json));
    }

    @Log(title = "获取项目/案卷/档案信息", businessType = BusinessType.SELECT)
    @PostMapping("/getmultipleinfo")
    public AjaxResult getmultipleinfo(@RequestBody JSONObject json) {
        return success(detailService.getmultipleinfo(json));
    }

    @Log(title = "根据项目id获取件列表", businessType = BusinessType.SELECT)
    @PostMapping("/getjianlistbyitemId")
    public TableDataInfo getjianlistbyitemId(@RequestBody JSONObject json) {
        List<Map<String, Object>> list = detailService.getjianlistbyitemId(json);
        return getDataTable(list);
    }

    @Log(title = "根据件ids获取件列表", businessType = BusinessType.SELECT)
    @PostMapping("/getjianlistbyjianids")
    public TableDataInfo getjianlistbyjianids(@RequestBody JSONObject json) {
        List<Map<String, Object>> list = detailService.getjianlistbyjianids(json);
        return getDataTable(list);
    }

    @Log(title = "预览大PDF，分割处理", businessType = BusinessType.OTHER)
    @PostMapping("/cutBigPdf")
    public AjaxResult viewBigPdf(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Long doc_id = Long.parseLong(request.getParameter("docId"));
        String daId = String.valueOf(request.getParameter("daId"));
        String categoryId = String.valueOf(request.getParameter("categoryId"));
        TenantCategory category = null;
        if (null == daId || "null".equals(daId)) {
            category = categoryMapper.selectTenantCategoryByID(Long.parseLong(categoryId), new TenantCategory().getTableName());
        } else {
            category = categoryMapper.getCategoryByDaId(new TenantCategory().getTableName(), new TenantYqda().getTableName(), Long.parseLong(categoryId));
        }
        TenantYqdaDocument document = documentMapper.viewByDocid(doc_id, category.getEfileTableName(), new Yqdatransdoc().getTableName());
        String url = document.getDocMnt() + File.separator + document.getPath();
        logger.info(url);
        File file = new File(url);
        JSONObject object = new JSONObject();
        List<String> imgPdfDesList = new ArrayList<>();
        String cutPdfPath = sysConfigService.selectConfigByKey("cutPdfPath");
        if(StringUtils.isEmpty(cutPdfPath)){
            logger.info("系统参数cutPdfPath未配置！");
            return new AjaxResult(-1, "不需要转换处理");
        }
        cutPdfPath = cutPdfPath+doc_id+File.separator;  //切割文件存储路径
        File cutPdfPathFile = new File(cutPdfPath);
        if(!cutPdfPathFile.exists()){
            cutPdfPathFile.mkdirs();
        }
        if ("PDF".equals(document.getDocFileType())) {
            if (file.exists()) {
                String bigPdfStr = sysConfigService.selectConfigByKey("BIGPDF");  //单位MB
                Long pdfSize = 1000l * 1024 * 1024; //默认1000MB
                if (StringUtils.isNotEmpty(bigPdfStr)) {
                    pdfSize = Long.valueOf(bigPdfStr) * 1024 * 1024;
                }
                //pdfSize = 1l;
                if (file.length() > pdfSize) {
                    //判断是否有处理过
                    String allPng = cutPdfPath+document.getRealDocName().substring(0, document.getRealDocName().lastIndexOf(".")) + "_all.png";
                    //根据pdf页数进行转图片
                    File imgPdfFile = new File(allPng);
                    if(imgPdfFile.exists()){
                        object.put("bigImg", DESUtil.encrypt(allPng));
                        File [] fileList = new File(imgPdfFile.getParent()).listFiles();
                        List<String> imgPath = new ArrayList<>();
                        for(File file1:fileList){
                            if(!file1.isDirectory() && !file1.getName().endsWith("_all.png")){
                                imgPath.add(DESUtil.encrypt(file1.getAbsolutePath()));
                            }
                        }
                        object.put("imgList",imgPath);
                        return AjaxResult.success(object);
                    }else {
                        List<String> imgPath = new ArrayList<>();
                        List<String> imgPdfList = PdfUtils.pdf2Img(url, cutPdfPath);
                        if (imgPdfList.size() > 1) {
                            //超过一页合成图片
                            //String substring = url.substring(0, url.lastIndexOf(".")) + "_all.png";
                            ImgUtils.mergeImage(true, imgPdfList, allPng);
                            object.put("bigImg", DESUtil.encrypt(allPng));
                        } else {

                        }

                        for (String imgPdf : imgPdfList) {
                            //判断图片大小
                            int[] wh = ImgUtils.imgWidthHeight(imgPdf);// [0] = 宽带  [1] = 高度
                            if (wh[0] > 13000) {
                                //分割6张
                                List<String> cupImg = ImgUtils.cutPic(6, 1, imgPdf, cutPdfPath);
                                imgPath.addAll(cupImg);
                            } else if (wh[0] > 8000) {
                                //分割4张
                                List<String> cupImg = ImgUtils.cutPic(4, 1, imgPdf, cutPdfPath);
                                imgPath.addAll(cupImg);
                            } else {
                                //分割2张
                                List<String> cupImg = ImgUtils.cutPic(2, 1, imgPdf, cutPdfPath);
                                imgPath.addAll(cupImg);
                            }
                        }
                        if (imgPdfList.size() == 1) {
                            File old = new File(imgPdfList.get(0));
                            old.renameTo(new File(allPng));
                            object.put("bigImg", DESUtil.encrypt(allPng));
                        }
                        logger.info(JSONArray.toJSONString(imgPath));

                        for (String img : imgPath) {
                            imgPdfDesList.add(DESUtil.encrypt(img));// 使用des加密返回，避免路径泄露
                        }
                        object.put("imgList", imgPdfDesList);
                        return AjaxResult.success(object);
                    }
                }else {
                    return new AjaxResult(-1, "不需要转换处理");
                }
            } else {
                throw new ServiceException("文件不存在！");
            }
        } else {
            throw new ServiceException("文件类型错误！");
        }

        //return AjaxResult.success(imgPdfDesList);
    }

    @Log(title = "预览分割后的PDF", businessType = BusinessType.OTHER)
    @PostMapping("/viewImg")
    public void viewImg(@RequestParam("file") String file, HttpServletResponse response) throws Exception {
        String filePath = DESUtil.decrypt(file);
        logger.info(filePath);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "inline; filename=\"" + new Date().getTime() + ".png" + "\"");
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(filePath)));
        byte[] buf = new byte[1024];
        int len = 0;
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        System.gc();
        br.close();
        out.close();
    }

    @GetMapping("/getViewImg")
    public void getHeadImage(@RequestParam("file") String file, HttpServletResponse response) throws IOException {
        OutputStream os = null;
        BufferedImage image = null;
        try {
            String filePath = DESUtil.decrypt(file);
            logger.info(filePath);
            image = ImageIO.read(new FileInputStream(new File(filePath)));
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
    }
}
